import error.Error;
import lexer.Lexer;
import llvmir.IrPrinter;
import parser.Parser;
import symbol.ScopeStack;
import mips.MipsBuilder;
import optimizer.Optimizer;

import java.io.IOException;

public class Compiler {
    public static void main(String[] args) {
        Lexer lexer = Lexer.getInstance();
        Parser parser = Parser.getInstance();
        ScopeStack scopeStack = ScopeStack.getInstance();
        Error error = Error.getInstance();
        IrPrinter irPrinter = IrPrinter.getInstance();
        MipsBuilder mipsBuilder = MipsBuilder.getInstance();
        Optimizer optimizer = Optimizer.getInstance();

        // 词法分析
        try {
            lexer.initBuffer("testfile.txt", "lexer.txt");
            while (lexer.getsym() != null) {
            }
            lexer.showLexer();
            lexer.closeBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 开启过程中优化
        optimizer.openAll();
        // 语法分析
        parser.setTokenList(lexer.getTokenList());
        try {
            parser.initBuffer("parser.txt");
            parser.showParser();
            parser.closeBuffer();

            scopeStack.initBuffer("symbol.txt");
            scopeStack.showSymbolTable();
            scopeStack.closeBuffer();

            error.initBuffer("error.txt");
            error.showError();
            error.closeBuffer();
            if (error.hasError) {
                System.exit(1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 开启中端优化和后端优化
        optimizer.start();
        // 中间代码生成
        try {
            irPrinter.initBuffer("llvm_ir.txt");
            irPrinter.showIr();
            irPrinter.closeBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 目标代码生成
        try {
            mipsBuilder.initBuffer("mips.txt");
            mipsBuilder.showMips();
            mipsBuilder.closeBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}